<?php
/**
 * 用户中心模型[新浪]
 * 
 * @version $Id: LoginSina.php 213 2012-01-10 08:18:15Z linsir123 $
 */
class modelLoginSina implements ILogin 
{
	/**
	 * @var 配置信息
	 */
	public $conf;
	
	/**
	 * 构造函数
	 */
	public function __construct()
	{
		$this->conf = App::O('member.sina');
		@session_start();
	}
	
	/**
	 * 取得授权类型
	 */
	public function getType()
	{
		return 'sina';
	}
	
	/**
	 * 取得唯一标识
	 */
	public function getKey()
	{
		return $_SESSION['sina']['uid'];
	}
	
	/**
	 * 取得用户呢称
	 */
	public function getNick()
	{
		$graphUrl = $this->_getGraphUrl();
		$info = $this->_queryUrl($graphUrl);
		$data = json_decode($info, true);
		return $data['screen_name'];
	}
	
	/**
	 * 登录URL
	 */
	public function getLoginUrl()
	{
		return "https://api.weibo.com/oauth2/authorize?client_id="
			. $this->conf['appid'] . "&response_type=code&redirect_uri="
			. urlencode($this->_getCallback());
	}
	
	/**
	 * 回调处理
	 */
	public function callbackHandler()
	{
		/// 取得token
		if ( ! isset($_SESSION['sina']['access_token'])) {
			list($url, $data) = $this->_getTokenUrl();
			$str = $this->_queryUrl($url, $data);
			$info = json_decode($str, true);
			if (isset($info['error'])) {
				var_dump($str);
				exit();
			}
			
			///
			$_SESSION['sina']['access_token'] = $info['access_token'];
			$_SESSION['sina']['uid'] = $info['uid'];
		}
		
		M::user()->loginOauth($this);
	}
	
	/**
	 * 回调URL
	 */
	public function _getCallback()
	{
		return str_replace(':80', '', lpUrl::__($this->conf['callback'], null, true));
	}
	
	/**
	 * 授权URL
	 */
	function _getTokenUrl()
	{
		return array(
			'https://api.weibo.com/oauth2/access_token',
			array(
				'client_id' => $this->conf['appid'],
				'client_secret' => $this->conf['appkey'],
				'redirect_uri' => $this->_getCallback(),
				'code' => $_REQUEST["code"],
			)
		);
	}
	
	/**
	 * 用户信息URL
	 */
	function _getGraphUrl()
	{
		return "https://api.weibo.com/2/users/show.json?access_token="
			. $_SESSION['sina']['access_token'] . "&uid="
			. $_SESSION['sina']['uid'];
	}
	
	/**
	 * 页面抓取
	 * // `CURL`访问`https`(关闭SSL验证)参考:
	 * // [http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/]
	 */
	function _queryUrl($url, $vars = array())
	{
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_FAILONERROR, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
		if (is_array($vars) && ! empty($vars)) {
			$list = "";
			foreach ($vars as $k => $v) 
				$list .= "$k=" . urlencode($v) . "&"; 
				
			curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, substr($list,0,-1));
		}
		
		///
		$result = curl_exec($ch);
		curl_close($ch);
		return $result;
	}
}
